#include "PeaksValleys.h"



PeaksValleys::PeaksValleys() :
	mRadius(100.0f), mTheta(0.0f), mPhi(PI*0.4f)
{
	mFX = 0; mTech = 0; mVertexLayout = 0;
	mVertexBuffer = 0;  mIndexBuffer = 0; mfxWVPVar = 0;
	mRadius = 100.0f; mTheta = 0.0F; mPhi = PI*0.4f;
	D3DXMatrixIdentity(&mView);
	D3DXMatrixIdentity(&mProj);
	D3DXMatrixIdentity(&mWVP);
}


PeaksValleys::~PeaksValleys()
{
}

void PeaksValleys::initApp(ID3D10Device * device)
{
	mDevice = device;
	m_peakValleys.init(mDevice, 129, 129, 1.0f);
	buildFX();
	buildVertexLayouts();
}
void PeaksValleys::onResize(int mClientWidth, int mClientHeight)
{
	float aspect = float(mClientWidth) / mClientHeight;
	D3DXMatrixPerspectiveFovLH(&mProj, 0.25f*PI, aspect, 1.0f, 1000.0f);
}

void PeaksValleys::updateScene(float deltatime, float gametime)
{
	float x = mRadius*cosf(0.5f*gametime);
	float z = mRadius*sinf(0.5f*gametime);
	float y = 50.0f*sinf(0.5f*gametime)+100;

	// Build the view matrix.
	D3DXVECTOR3 pos(x, y, z);
	D3DXVECTOR3 target(0.0f, 0.0f, 0.0f);
	D3DXVECTOR3 up(0.0f, 1.0f, 0.0f);
	D3DXMatrixLookAtLH(&mView, &pos, &target, &up);
}

void PeaksValleys::Draw()
{
	mDevice->OMSetDepthStencilState(0, 0);
	float blendFactors[] = { 0.0f, 0.0f, 0.0f, 0.0f };
	mDevice->OMSetBlendState(0, blendFactors, 0xffffffff);
	mDevice->IASetInputLayout(mVertexLayout);
	mDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);


	D3D10_TECHNIQUE_DESC techDesc;
	mTech->GetDesc(&techDesc);
	for (UINT p = 0; p < techDesc.Passes; ++p)
	{
		mWVP = mView*mProj;
		mfxWVPVar->SetMatrix((float*)&mWVP);
		mTech->GetPassByIndex(p)->Apply(0);
		m_peakValleys.draw();
	}
}

void PeaksValleys::buildFX()
{
	string currentPath = MyMethods::GetCurrentPath();

	string fxPath = currentPath + "\\..\\fxes\\color.fx";
	DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
	shaderFlags |= D3D10_SHADER_DEBUG;
	shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
#endif
	ID3D10Blob * compilationErrors = 0;
	HRESULT hr = 0;
	hr = D3DX10CreateEffectFromFile(MyMethods::stringToLPCWSTR(fxPath), 0, 0,
		"fx_4_0", shaderFlags, 0, mDevice, 0, 0, &mFX, &compilationErrors, 0);
	if (FAILED(hr))
	{
		if (compilationErrors)
		{
			MessageBoxA(0, (char*)compilationErrors->GetBufferPointer(), 0, 0);
			ReleaseCOM(compilationErrors);
			return;
		}
	}

	mTech = mFX->GetTechniqueByName("ColorTech");
	mfxWVPVar = mFX->GetVariableByName("gWVP")->AsMatrix();
}

void PeaksValleys::buildVertexLayouts()
{
	D3D10_INPUT_ELEMENT_DESC vertexDesc[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
		{ "COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }
	};

	// Create the input layout
	D3D10_PASS_DESC PassDesc;
	mTech->GetPassByIndex(0)->GetDesc(&PassDesc);
	HRESULT hr = 0;

	hr = mDevice->CreateInputLayout(vertexDesc, 2, PassDesc.pIAInputSignature,
		PassDesc.IAInputSignatureSize, &mVertexLayout);
}
